package com.example.balls;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.TextView;

public class BoardActivity extends Activity {

	private final static Integer LENGHT = 6;
	private final static Integer COUNT = 5;
	private final static Integer BALL_BG = 0;
	private final static Integer BALL_WHITE = 1;
	private final static Integer BALL_POINT = 2;
	private final static Integer BALL_BLACK = 9;
	private Animation animScale;
	private Context context;
	private SoundPool soundPool;
	private AudioManager audioManager;
    private int soundStep;
	private Integer point_x;
	private Integer point_y;
	private Integer level = 0;
	private Boolean volume = false;
	private Integer[][] board = new Integer[][] {{0,0,0,0,0,0},
												 {0,0,0,0,0,0},
												 {0,0,0,0,0,0},
												 {0,0,0,0,0,0},
												 {0,0,0,0,0,0},
												 {0,0,0,0,0,0}};
	
	private final ImageButton[][] imgs = new ImageButton[LENGHT][LENGHT];
	private final Integer[] cells = new Integer[LENGHT];
	private TextView textLevel;
			
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_board);
        initialize();
        setClickListeners();
        level = getIntent().getExtras().getInt("level");
        volume = getIntent().getExtras().getBoolean("volume");
        
        textLevel = (TextView) findViewById(R.id.textLevel);
        
        if(volume){
	        soundPool = new SoundPool(8, AudioManager.STREAM_MUSIC, 0);
	        soundStep = soundPool.load(this, R.raw.step, 1);
        }
        
        final ImageButton btnBack = (ImageButton) findViewById(R.id.imgBack);  
        btnBack.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(BoardActivity.this, MainActivity.class);
				intent.putExtra("volume", volume);
				finish();
				startActivity(intent);
			}
        });
        
        final ImageButton btnRefresh = (ImageButton) findViewById(R.id.imgRefresh);       
        btnRefresh.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setLevel(level);
			}
        });
        
        setLevel(level);
    }
    
    private void refresh(){
    	boolean gameOver = true;
    	for (int i = 0; i < LENGHT; i++) {
    		for (int j = 0; j < LENGHT; j++) {
    			if(board[i][j].equals(BALL_BG)){
    				imgs[i][j].setBackgroundResource(R.drawable.ic_ball_bg);
    				gameOver = false;
    			} else if(board[i][j].equals(BALL_WHITE))
    				imgs[i][j].setBackgroundResource(R.drawable.ic_ball_yellow);
    			else if(board[i][j].equals(BALL_BLACK))
    				imgs[i][j].setBackgroundResource(R.drawable.ic_ball_black);
    			else if(board[i][j].equals(BALL_POINT)){
    				imgs[i][j].setBackgroundResource(R.drawable.ic_ball_green);
    				imgs[i][j].setAnimation(animScale);
    			}
    		}
		}
    	
    	if(gameOver) {
    		context = BoardActivity.this;
    		String title = "Congratulations";
    		String button1String = "Next level";
    		String button2String = "Again";
    		
    		AlertDialog.Builder ad = new AlertDialog.Builder(context);
    		ad.setTitle(title);
    		ad.setPositiveButton(button1String, new OnClickListener() {
    			public void onClick(DialogInterface dialog, int arg1) {
    				level++;
    				if(level<36) setLevel(level);
    				else {
    					Intent intent = new Intent(BoardActivity.this, MainActivity.class);
    					intent.putExtra("volume", volume);
    					startActivity(intent);
    				}
    			}
    		});
    		ad.setNegativeButton(button2String, new OnClickListener() {
    			public void onClick(DialogInterface dialog, int arg1) {
    				setLevel(level);
    			}
    		});
    		ad.setCancelable(false);
    		ad.show();
    	}
    }
    
    private Boolean checkPoint(){
    	for (int i = 0; i < LENGHT; i++) {
    		for (int j = 0; j < LENGHT; j++) {
    			if(board[i][j].equals(BALL_POINT)){
    				imgs[i][j].setBackgroundResource(R.drawable.ic_ball_green);
    				point_x = i;
    				point_y = j;
    				return true;
    			}
    		}
		}
    	return false;
    }
    
    private void setClickListeners(){
    	for (int i = 0; i < LENGHT; i++) {
    		for (int j = 0; j < LENGHT; j++) {
    			setClick(imgs[i][j], cells[i], cells[j]);
    		}
		}
    }
    
    private void setClick(final ImageButton button, final Integer i, final Integer j){
    	button.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Integer moveCount = Integer.valueOf(0);
				if(!checkPoint()){ 
					if(board[i][j].equals(BALL_BG)) board[i][j] = BALL_POINT;
				} else {
					Integer num_x = Integer.valueOf(point_x);
					Integer num_y = Integer.valueOf(point_y);
					moveCount = move(i,j);
					switch (moveCount) {
						//up
						case 1:
							board[num_x][j] = BALL_WHITE;
							while (num_x > 0) {
								num_x--;
								if(board[num_x][j].equals(BALL_BG) && num_x > 0){
									board[num_x][j] = BALL_WHITE;
								} else if(!board[num_x][j].equals(BALL_BG)){
									board[num_x+1][j] = BALL_POINT;
									break;
								} else if(num_x <= 0) {
									board[num_x][j] = BALL_POINT;
									break;
								}
							}
							break;
						//left
						case 2:
							board[i][num_y] = BALL_WHITE;
							while (num_y > 0) {
								num_y--;
								if(board[i][num_y].equals(BALL_BG) && num_y > 0){
									board[i][num_y] = BALL_WHITE;
								} else if(!board[i][num_y].equals(BALL_BG)){
									board[i][num_y+1] = BALL_POINT;
									break;
								} else if(num_y <= 0) {
									board[i][num_y] = BALL_POINT;
									break;
								}
							}
							break;
						//down
						case 3:
							board[num_x][j] = BALL_WHITE;
							while (num_x < COUNT) {
								num_x++;
								if(board[num_x][j].equals(BALL_BG) && num_x < COUNT){
									board[num_x][j] = BALL_WHITE;
								} else if(!board[num_x][j].equals(BALL_BG)){
									board[num_x-1][j] = BALL_POINT;
									break;
								} else if(num_x >= COUNT) {
									board[num_x][j] = BALL_POINT;
									break;
								}
							}
							break;
						//right
						case 4:
							board[i][num_y] = BALL_WHITE;
							while (num_y < COUNT) {
								num_y++;
								if(board[i][num_y].equals(BALL_BG) && num_y < COUNT){
									board[i][num_y] = BALL_WHITE;
								} else if(!board[i][num_y].equals(BALL_BG)){
									board[i][num_y-1] = BALL_POINT;
									break;
								} else if(num_y >= COUNT) {
									board[i][num_y] = BALL_POINT;
									break;
								}
							}
							break;
						//null
						case -1:
							break;
					}
				}
				refresh();
				
				if(moveCount > 0 && volume){
					audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
			            float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			            float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			            float volume = actualVolume / maxVolume;
			            soundPool.play(soundStep, volume, volume, 1, 0, 1f);
				}
			}
        });
    	
    	animScale.setAnimationListener(new Animation.AnimationListener(){        
    	    public void onAnimationEnd(Animation arg0) {}    	    
			public void onAnimationRepeat(Animation animation) { }
			public void onAnimationStart(Animation animation) { }
    	});
    }
    
    private Integer move(final Integer i, final Integer j){
    	if(i.equals(point_x)){
    		if((j-point_y) < 0) return 2;
    		if((j-point_y) > 0) return 4;
    	}
    	if(j.equals(point_y)){
    		if((i-point_x) < 0) return 1;
    		if((i-point_x) > 0) return 3;
    	}
    	return -1;
    }
    
    private void setLevel(Integer level){
    	cleanBoard();
    	
    	switch (level) {
		case 0:
			board[5][0] = BALL_BLACK;
			break;
		case 1:
			board[0][5] = BALL_BLACK;
			board[1][3] = BALL_BLACK;
			break;
		case 2:
			board[0][0] = BALL_BLACK;
			board[1][2] = BALL_BLACK;
			board[3][3] = BALL_BLACK;
			board[5][0] = BALL_BLACK;
			break;
		}
    	
    	Integer lvl = level + 1; 
        textLevel.setText(lvl.toString());
    	refresh();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_board, menu);
        return true;
    }
    
    private void cleanBoard(){
    	for (int i = 0; i < LENGHT; i++) {
    		for (int j = 0; j < LENGHT; j++) {
    			board[i][j] = BALL_BG;
    		}			
		}
    }

    private void initialize(){
    	imgs[0][0] = (ImageButton) findViewById(R.id.btn00);
    	imgs[0][1] = (ImageButton) findViewById(R.id.btn01);
    	imgs[0][2] = (ImageButton) findViewById(R.id.btn02);
    	imgs[0][3] = (ImageButton) findViewById(R.id.btn03);
    	imgs[0][4] = (ImageButton) findViewById(R.id.btn04);
    	imgs[0][5] = (ImageButton) findViewById(R.id.btn05);

    	imgs[1][0] = (ImageButton) findViewById(R.id.btn10);
    	imgs[1][1] = (ImageButton) findViewById(R.id.btn11);
    	imgs[1][2] = (ImageButton) findViewById(R.id.btn12);
    	imgs[1][3] = (ImageButton) findViewById(R.id.btn13);
    	imgs[1][4] = (ImageButton) findViewById(R.id.btn14);
    	imgs[1][5] = (ImageButton) findViewById(R.id.btn15);

    	imgs[2][0] = (ImageButton) findViewById(R.id.btn20);
    	imgs[2][1] = (ImageButton) findViewById(R.id.btn21);
    	imgs[2][2] = (ImageButton) findViewById(R.id.btn22);
    	imgs[2][3] = (ImageButton) findViewById(R.id.btn23);
    	imgs[2][4] = (ImageButton) findViewById(R.id.btn24);
    	imgs[2][5] = (ImageButton) findViewById(R.id.btn25);

    	imgs[3][0] = (ImageButton) findViewById(R.id.btn30);
    	imgs[3][1] = (ImageButton) findViewById(R.id.btn31);
    	imgs[3][2] = (ImageButton) findViewById(R.id.btn32);
    	imgs[3][3] = (ImageButton) findViewById(R.id.btn33);
    	imgs[3][4] = (ImageButton) findViewById(R.id.btn34);
    	imgs[3][5] = (ImageButton) findViewById(R.id.btn35);

    	imgs[4][0] = (ImageButton) findViewById(R.id.btn40);
    	imgs[4][1] = (ImageButton) findViewById(R.id.btn41);
    	imgs[4][2] = (ImageButton) findViewById(R.id.btn42);
    	imgs[4][3] = (ImageButton) findViewById(R.id.btn43);
    	imgs[4][4] = (ImageButton) findViewById(R.id.btn44);
    	imgs[4][5] = (ImageButton) findViewById(R.id.btn45);

    	imgs[5][0] = (ImageButton) findViewById(R.id.btn50);
    	imgs[5][1] = (ImageButton) findViewById(R.id.btn51);
    	imgs[5][2] = (ImageButton) findViewById(R.id.btn52);
    	imgs[5][3] = (ImageButton) findViewById(R.id.btn53);
    	imgs[5][4] = (ImageButton) findViewById(R.id.btn54);
    	imgs[5][5] = (ImageButton) findViewById(R.id.btn55);
    	
    	animScale = AnimationUtils.loadAnimation(this, R.anim.scale);
    	
    	for (int i = 0; i < LENGHT; i++) {
			cells[i] = i;
		}
    }
}
